/*
 ============================================================================
 Name        : phase_para.c
 Author      : chenf
 Version     :
 Copyright   : loongsec
 Description : CRUD phase_parm table, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"
#include "stdx.h"

void putJSON(char **azResult, int nrow, int ncolumn);
void putHTML(char **azResult, int nrow, int ncolumn);

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("%s.\n", err_msg);
}

int main(void) {
    sqlite3  *db  = NULL;
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    char     *input;
    char     *req_method;
    int      rc;
/*
    if(isvalid_cookie()!=0){
        putError();
    	return 0;
	}
*/
    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        put_error(sqlite3_errmsg(db));
        return 0;

    } else {

    	req_method = getenv("REQUEST_METHOD");

		FILE* fp = (FILE*) stdin;
	    input = getcgidata(fp, req_method);

	    PARAM id = getParam(input, "id");

	    PARAM dataType = getParam(input, "dataType");

	    if( strcmp(id.value, "") != 0 && strcmp(id.value, "null") != 0 ){
			 sprintf(sql, "select * from [tb_phase_parm] where phase_index = %s ", id.value);
		} else {
			 sprintf(sql, "select * from [tb_phase_parm]");
		}

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            put_error(zErrMsg);
            sqlite3_close(db);
            return 0;

        } 
        if (*azResult != NULL) {
            // choose data format
            if( strcmp(dataType.value, "json") == 0 ){
			 	putJSON(azResult, nrow, ncolumn);
			} else {
				putHTML(azResult, nrow, ncolumn);
			}
			//printf("%s", sql);
			//printf("************* dataType.value %d\n",dataType.value);
        }
    }

    sqlite3_close(db);
    return 0;

}




void putJSON(char **azResult, int nrow, int ncolumn){
	int i=0, j=0, n=0;
	printf("Content-type:text/json;charset=UTF-8\n\n");
	printf("{ \"rows\": \"%d\", \"data\": [", nrow);
    for(i=1; i<=nrow; i++) {
        printf("{");
		char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
			if(j==0){
				phaseIndex = azResult[ (i*ncolumn) + j ];
			}
			printf("\"%s\": \"", azResult[j]);

			if(j==9 || j==10){
				char t[100];
				printf("%s", _itoa(
							atoi(  azResult[ (i*ncolumn) + j ] ),
							t, 2) );
			} else{
				printf("%s", azResult[ (i*ncolumn) + j ]);
			}
            //printf(azResult[ (i*ncolumn) + j ]);

            if(j == ncolumn-1)
				printf("\"");
			else
				printf("\",");
            n++;
        }
        if(i == nrow)
			printf("}\n\n");
		else
			printf("},\n\n");
    }
    printf("]}");
}


void putHTML(char **azResult, int nrow, int ncolumn){
	int i=0, j=0, n=0;
	printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("<table res=\"%d\" id=\"phase\">", nrow);
    printf("<tr>\
		<td>相位序号</td>\
		<td>行人过街绿灯时长(秒)</td>\
		<td>行人清空时间(秒)</td>\
		<td>最小绿灯时间(秒)</td>\
		<td>单位绿灯延长时间(秒)</td>\
		<td>最大绿灯时间1(秒)</td>\
		<td>最大绿灯时间2(秒)</td>\
		<td>弹性相位固定绿灯时间(秒)</td>\
		<td>绿闪时间(秒)</td>\
		<td>相位类型</td>\
		<td>相位选项功能</td>\
		<td>扩展</td>\
		<td>修改时间</td>\
		<td>选项</td></tr>\n\n");
    for(i=1; i<=nrow; i++) {
        printf("<tr>");
		char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
			if(j==0){
				phaseIndex = azResult[ (i*ncolumn) + j ];
			}
			printf("<td>");

			if(j==9 || j==10){
				char t[100];
				printf("%s", _itoa(
							atoi(  azResult[ (i*ncolumn) + j ] ),
							t, 2) );
			} else{
				printf("%s", azResult[ (i*ncolumn) + j ]);
			}

            printf("</td>");
            n++;
        }
        printf("<td>\
              		<input type=\"button\" value=\"编辑\" onclick=\"editPhase(%s)\"   />\
              		<input type=\"button\" value=\"删除\" onclick=\"deletePhase(%s)\" />\
              </td>", phaseIndex, phaseIndex);
        printf("<tr>\n\n");
    }
    printf("</table>");
}

